package utils;

import play.Logger;

import javax.script.ScriptContext;
import javax.script.ScriptEngine;
import javax.script.ScriptEngineManager;
import java.util.Map;

/**
 * 脚本工具
 * @author zhangzc
 * @since 2017/8/10
 */
public class ScriptUtil {

    public static <T> T runJS(String script, Map<String, Object> context){
        try{
            ScriptEngineManager m = new ScriptEngineManager();
            ScriptEngine nashorn = m.getEngineByName("nashorn");
            ScriptContext cxt = nashorn.getContext();
            if(context != null){
                context.forEach((k,v)->{
                    cxt.setAttribute(k, v, ScriptContext.GLOBAL_SCOPE);
                });
            }

            Object result = nashorn.eval(script);
            return (T) result;
        }catch (Exception e){
            Logger.error(e, "Error in ScriptUtil.run()");
            return null;
        }
    }
}
